import copy
from django.db.models import Q


class HideDefaultDomainFieldMixin:
    """Hide user field"""

    def get_fields(self, req, obj=None):
        fields = list(super().get_fields(req, obj))

        if req.user.is_superuser:
            return fields

        try:
            # hide the user field.
            fields.remove('default')
            # fields.remove('default')
        except ValueError:
            pass
        return fields

    def get_fieldsets(self, req, obj=None):
        fieldsets = super().get_fieldsets(req, obj)

        if req.user.is_superuser:
            return fieldsets

        new_fieldsets = copy.deepcopy(fieldsets)
        for _, d in new_fieldsets:
            try:
                temp_list = list(d['fields'])
                temp_list.remove('default')
                # temp_list.remove('default')
                d['fields'] = temp_list
            except ValueError:
                pass

        return new_fieldsets


class HideUserFieldMixin:
    """Hide user field"""

    def get_list_display(self, req):
        fields = list(super().get_list_display(req))

        if req.user.is_superuser:
            return fields

        try:
            # hide the user field.
            fields.remove('user')
            # fields.remove('default')
        except ValueError:
            pass
        return fields

    def get_fields(self, req, obj=None):
        fields = list(super().get_fields(req, obj))

        if req.user.is_superuser:
            return fields

        try:
            # hide the user field.
            fields.remove('user')
        except ValueError:
            pass
        return fields

    def get_fieldsets(self, req, obj=None):
        fieldsets = super().get_fieldsets(req, obj)

        if req.user.is_superuser:
            return fieldsets

        new_fieldsets = copy.deepcopy(fieldsets)
        for _, d in new_fieldsets:
            try:
                temp_list = list(d['fields'])
                temp_list.remove('user')
                d['fields'] = temp_list
            except ValueError:
                pass

        return new_fieldsets


class ShowUserOwnDataMixin:
    """Show just users data/rows"""

    def get_queryset(self, req):
        qs = super().get_queryset(req)
        if req.user.is_superuser:
            return qs
        return qs.filter(Q(user=req.user))


class ShowDefaultDomainsMixin:
    """Show active default domains as well"""

    def get_queryset(self, req):
        from .models import Domain

        qs = super().get_queryset(req)
        if req.user.is_superuser:
            return qs
        return qs | Domain.objects.filter(
            Q(default=True, status=Domain.STATUS.ACTIVE))
